  var preloading = false;
  function onStateChanged(evt){
	if(evt == 0){
      var tvPlayer = document.getElementById('myytplayer');
      // find what to display right now
      var oldVideoIndex = videoIndex;
      var videosLength = videos.length; // save because of multiple threads
      videoIndex = findNotSkippedVideo(videoIndex + 1);
      if(videoIndex == -1){
        if(preloading){
          // preloading, display anything
          videoIndex = videosLength;
        }
        else{
          //nothing to display
          alert('Riched the end of video list');
          return;
        }
      }
      if(!preloading){
        // find and may be preload video to be displayed next time
        var nextNotSkippedVideo = findNotSkippedVideo(videoIndex + 1);
        if(nextNotSkippedVideo == - 1){ // load more
          preloadVideos(videos.length);
        }
      }

      var oldFilmFrame = getFilmFrame(oldVideoIndex);
      removeCssClass(oldFilmFrame, 'selected');
      var newFilmFrame = getFilmFrame(videoIndex);
      newFilmFrame.className += 'selected';
            
      tvPlayer.loadVideoByUrl("http://www.youtube.com/e/" + videos[videoIndex]);
      new Ajax.Request('/watchingHistory/watch/' + videos[videoIndex], {asynchronous:true});
      if(videos.length > videoIndex + 2){
    	mayBeSkipVideo(videoIndex + 1);
      }
	}
  }
  function onPlayerError(evt){
    if(evt != 2){
      onStateChanged(0);
    }
  }
  // Preload videos until not skipped video found. Otherwise do nothing.
  function preloadVideos(index){
	preloading = true;
    new Ajax.Request('/videoCategory/search/' + currentVideoCategoryFeed + '/' + currentVideoCategoryTime + '?startIndex=' + index, 
              { method:'get',
        onSuccess: function(transport, json){
          json = transport.responseText.evalJSON();
          for(var i = 0; i < json.vids.length; i++){
            videos[json.startInd + i] = json.vids[i];
          }
          mayBeSkipVideo(json.startInd);
          var notSkippedInd = findNotSkippedVideo(json.startInd)
          if(notSkippedInd == -1 && json.vids.length > 0) {
        	preloadVideos(json.startInd + json.vids.length);
          }
          else {
        	preloading = false;
          }
        }
    });
  }
  function findNotSkippedVideo(index){
    if(index >= skippedVideos.length && skippedVideos.length < videos.length){
      mayBeSkipVideo(index);
    }
    while(index < skippedVideos.length){
      if(!skippedVideos[index])
        return index;
      index++;
    }
    return -1;
  }
  function onYouTubePlayerReady(playerId){
    var tvPlayer = document.getElementById('myytplayer');
    tvPlayer.addEventListener("onStateChange", "onStateChanged");
    tvPlayer.addEventListener("onError", "onPlayerError");
  }
  var skippedVideos = [];
  function mayBeSkipVideo(index){
    if(videos.length < index + 1)
      return;
    if(skippedVideos.length > index +1){
      return;
    }
    if(!avoidDuplicates()){
      skippedVideos[index] = false;
      return;
    }
	new Ajax.Request('/watchingHistory/skip/' + videos[index], {asynchronous:false,
		onSuccess: function(transport){
          var skip = (transport.responseText == 'true');
          skippedVideos[index] = skip;
          if(skip){
            var frame = getFilmFrame(index);
            frame.className += ' skipped';
        	mayBeSkipVideo(index + 1);
          }
        }
      });
  }
  function checkInitialVideos(index){
    mayBeSkipVideo(index);
    var nextNotSkippedVideo = findNotSkippedVideo(index);
    if(nextNotSkippedVideo == - 1){ // load more
      preloadVideos(videos.length);
    }
  }
  function avoidDuplicates(){
	return document.getElementById('avoidDuplicates').checked;
  }
  function getFilmFrame(index){
    return document.getElementById('filmFrame' + index);
  }
  function avoidDuplicatesChanged(){
    for(var i = videoIndex + 1; i < skippedVideos.length; i++){
      var filmFrame = getFilmFrame(i);
      removeCssClass(filmFrame, 'skipped');
    }
    skippedVideos = skippedVideos.slice(0, videoIndex + 1);
    //mayBeSkipVideo(videoIndex + 1);
    checkInitialVideos(videoIndex + 1);
  }
  function removeCssClass(el, className){
	  el.className = el.className.replace(className, '');
  }
